package com.example.cp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.cp.config.HiddenProperties;
import com.example.cp.config.WxCpConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;

/**
 * Created by hemin on 2019/8/8.
 */
@Api("网页授权登录")
@Controller
@RequestMapping("/oauth")
@Slf4j
public class OAuth2Controller {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    HiddenProperties hiddenProperties;

    /**
     * 接收来自菜单点击的消息，获取用户信息，重定向到微信获取code
     * @param agentId 应用ID
     * @return
     */
    @GetMapping("/{agentId}")
    @ApiOperation(value = "获取code",notes = "接收来自菜单点击的消息，拼装链接，发送请求获取code")
    @ApiImplicitParam(name = "agentId",value = "应用ID",required = true,dataType = "String")
    public String authGet(@PathVariable Integer agentId) {
        WxCpService cpService = WxCpConfiguration.getCpService(agentId);
        String authorizationUrl = cpService.getOauth2Service().buildAuthorizationUrl(URLEncoder.encode(hiddenProperties.getRedirectUrl() + "/oauth/code"),agentId.toString());
        return "redirect:"+authorizationUrl;
    }

    /**
     * 授权登录后处理业务方法
     * @param code
     * @param state
     * @param modelMap
     * @return
     */
    @GetMapping("/code")
    @ApiOperation(value = "授权登录",notes = "根据code获取userId，根据userId跳转不同页面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code",value = "企业微信code",required = true,dataType = "String"),
            @ApiImplicitParam(name = "state",value = "企业微信state",required = true,dataType = "String"),
    })
    public String code(@RequestParam("code") String code,
                     @RequestParam("state")String state,
                     ModelMap modelMap) {
        WxCpService cpService = WxCpConfiguration.getCpService(Integer.valueOf(state));
        String[] res = new String[0];
        try {
            res = cpService.getOauth2Service().getUserInfo(code);
            log.info("企业微信人员信息 openId：{}",res[0]);
            log.info("企业微信人员信息 deviceId：{}",res[1]);
            String userId = res[0];
            modelMap.put("openId",userId);
            modelMap.put("deviceId",res[1]);
            //获取用户信息
            String url = hiddenProperties.getHeaderUrl() + "/userInfo/isBind?userId="+userId;
            log.info("请求url：{}",url);
            JSONObject result = restTemplate.getForObject(url, JSONObject.class);
            log.info("请求回调信息：{}",res);
            modelMap.put("msg",result.getString("statusMsg"));
            modelMap.put("data",result.getJSONObject("data").toJSONString());
            //如果已绑定则跳转到隐患首页
            if(result.getInteger("statusCode") == 0){
                String id = (String) result.getJSONObject("data").get("id");
                //获取隐患通报数据
                /*JSONObject forObject = restTemplate.getForObject(hiddenProperties.getHeaderUrl() + "/danger/report?userId=" + id, JSONObject.class);
                modelMap.put("report",forObject);*/
                //获取隐患首页数据 1.隐患首页数据 2.隐患通报
                /*String latestUrl = hiddenProperties.getHeaderUrl() + "/danger/latest?userId="+id+"count=6";
                JSONArray latests = restTemplate.getForObject(latestUrl, JSONArray.class);
                modelMap.put("latests",latests);*/
                return "system/hidden/index_";
            }else{
                return "bind";
            }
        } catch (Exception e) {
            log.error("授权登录错误日志：{}",e.getMessage());
            e.printStackTrace();
            return "error";
        }
    }

}
